package com.cslg.interceptor;


import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class CheckUserInterceptor implements HandlerInterceptor {
    //在执行 Handle 之前执行，返回值：true:放行  false:拦截
    // 应用场景：检查用户是否登陆
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        //检测用户是否登陆
        HttpSession session = request.getSession();
        //有些页面是不能拦截的，如登陆和注册页面
        String path = request.getRequestURI();
        if (path.indexOf("login")!=-1 || path.indexOf("register.do")!=-1){
            return true;
        }

        if (session.getAttribute("user") != null){
            System.out.println("用户已经登陆");
            return true;
        }else {
            System.out.println("用户未登陆");
            //跳转到登陆页面
            response.sendRedirect(request.getContextPath()+"/index.jsp");
            return false;
        }

    }
    //在最后一行代码之后，且在 return 之前执行
    // 应用场景：需要根据某种业务规则，重新修改 modelAndView
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {

    }
    //在执行 Handle 之后执行
    //应用场景：做日志记录可用此方法
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {

    }
}
